package ArrayList存储学生对象并排序;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;

public class CollectionDemo {
    public static void main(String[] args) {
        ArrayList<Student>array=new ArrayList<Student>();
        Student student = new Student();
        Student s1=new Student("姜恒星",30);
        Student s2=new Student("姜恒",20);
        Student s3=new Student("姜",10);
        Student s4=new Student("刘",30);
        array.add(s1);
        array.add(s2);
        array.add(s3);
        array.add(s4);

        //使用Collection对ArrayList集合排序
        //sort (List<T> list, Comparator<? super T) c)
        Collections.sort(array, new Comparator<Student>() {
            @Override
            public int compare(Student s1, Student s2) {//匿名内部类

                //按年龄从小到大排序，年龄相同时，按姓名的字母顺序排序
                int num=s1.getAge()-s2.getAge();
                int num1= num==0?s1.getName().compareTo(s2.getName()):num;
                return num1;
            }
        });
     for (Student s:array){
         System.out.println(s.getName()+","+s.getAge());
     }
    }
}
